package ch.ffhs.ks.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.SwingWorker;

import ch.ffhs.ks.model.Account;
import ch.ffhs.ks.model.Mail;
import ch.ffhs.ks.model.ModelContext;

public class MailSender extends SwingWorker<Object, Object> {

	private Mail mail;
	private Account account;
	private ModelContext modelContext;
	
	public MailSender(Mail mail, Account account, ModelContext modelContext)
	{
		this.mail = mail;
		this.account = account;
		this.modelContext = modelContext;
	}

	@Override
	protected void done() {
		
		super.done();
		
		modelContext.notifyProgress("Email wurde erfolgreich versendet");
	}

	@Override
	protected Object doInBackground()  {

		final String username = account.getEmailAddress();
		final String password = account.getPassword();

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", account.getSmtpAddress());
		props.put("mail.smtp.port", account.getSmtpPort());

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(account.getEmailAddress()));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(mail.getReceiver()));
			message.setSubject(mail.getSubject());
			message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.getCc()));
			message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.getBcc()));
			message.setText(mail.getContent());

			Transport.send(message);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return null;

	}

}
